<?php

class SiteController extends BaseController {

    public function actionIndex() {
        $model = new SubscForm(); 
        if(isset($_POST['SubscForm'])) {
            if($model->validate()) 
                Yii::app()->db->createCommand()->insert('subscribers', array('email'=>$model->email, 'type'=>'partner', 'unreg'=>'1'));
        }
        $this->brending('index');
        $newPartners = Yii::app()->db->createCommand()->select('p.url, p.name, p.partnerid, p.type, p.refLink, p.about, c.catId, c.name as catName')->from('partners p')->join('partners_cat c', 'c.catId=p.catId')->limit(6)->order('p.date DESC')->queryAll();
        if(!empty($newPartners)) {
            $idArr = array();
            for($i=0;$i<count($newPartners); $i++) $idArr[] = $newPartners[$i]['partnerid'];
            $newPartSubCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            if(!empty($newPartSubCats)) {
                for($i=0;$i<count($newPartners); $i++) {
                    for($j=0;$j<count($newPartSubCats); $j++) 
                        if($newPartSubCats[$j]['partnerId'] == $newPartners[$i]['partnerid']) $newPartners[$i]['subCats'][] = $newPartSubCats[$j];
                }
            }
        }
        $cats = Yii::app()->db->createCommand()->select('c.name as catName, c.catId as categoryId, c.reviewRating1, c.reviewRating2, c.reviewRating3, c.reviewRating4, c.parentId, c.ratingRules as catratingrules, b.code')->from('partners_cat c')->leftJoin('banners_relations r', 'r.catId=c.catId')->leftJoin('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной"')->where('parentId=0')->group('c.catId')->queryAll();
        if(!empty($cats)) {
            $sql = '';
            $idArr = array();
            for ($i=0; $i<count($cats); $i++) {
                $idArr[] = $cats[$i]['categoryId'];
                if($i) $sql .= ' UNION ';
                $sql .= '('.Yii::app()->db->createCommand()->select('p.url, p.partnerid, p.name, p.editorMark, p.catId, p.openDate, p.openDate, p.about, p.isClose, s.mean, s.field1, s.field2, s.field3, s.field4, s.oldMean, s.oldField1, s.oldField2, s.oldField3, s.oldField4, s.votes, c.catId, c.parentId')->from('partners p')->leftJoin('partners_cat_score s', 's.partnerId=p.partnerid')->join('partners_cat c', 'p.catId=c.catId')->where('(p.catId='.$cats[$i]['categoryId'].' or c.parentId = '.$cats[$i]['categoryId'].') and p.zeroPosition = 0')->limit(5)->text.')';
            }
            $sql .= ';'; 
            $partners = Yii::app()->db->createCommand($sql)->query()->readAll();
            $zeroPartners = Yii::app()->db->createCommand()->select('p.about, p.catId, p.url, p.name')->from('partners p')->where('p.catId IN('.implode(',', $idArr).') and p.zeroPosition = 1')->queryAll();
            if(!empty($partners)) {    
                for($j=0; $j<count($partners); $j++) $idArr[] = $partners[$j]['partnerid'];
            }  
            $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where(array('in', 'partnerId', $idArr))->queryAll();
            for($i=0; $i<count($cats); $i++) {
                if(!empty($zeroPartners)) {
                    foreach ($zeroPartners as $k=>$v) {
                        if($v['catId'] == $cats[$i]['categoryId']) $cats[$i]['zeroPart'][] = $zeroPartners[$k];
                    }
                }
                if(!empty($partners)) {    
                    for($j=0; $j<count($partners); $j++) {
                        $partners[$j]['subcats'] = array();
                        for($l=0; $l<count($subCats); $l++) {
                            if($subCats[$l]['partnerId'] == $partners[$j]['partnerid']) $partners[$j]['subcats'][] = $subCats[$l]; 
                        }
                        if($partners[$j]['catId'] == $cats[$i]['categoryId'] || $partners[$j]['parentId'] == $cats[$i]['categoryId']) {
                            if(!empty($partners[$j]['subcats'])) {
                                $subStr ='<ul  class="inline unstyled home_subcats">';
                                for($n=0; $n<count($partners[$j]['subcats']); $n++) { 
                                    $subStr .= '<li class="subcats'.$n.'">'.CHtml::link($partners[$j]['subcats'][$n]['name'], Yii::app()->createUrl('partner/default/cat', array('catId'=>$partners[$j]['subcats'][$n]['catId'], 'parentId'=>$partners[$j]['subcats'][$n]['parentId']))).'</li>&nbsp;&nbsp;';
                                }
                                $subStr.="</ul>";
                                $partners[$j]['subcats'] = $subStr;
                            }
                            $cats[$i]['part'][] = $partners[$j];
                        }
                    }    
                }  
            }
            for($i=0; $i<count($cats); $i++) {
                $data = array();
                if(!empty($cats[$i]['part'])) {
                    for($j=0; $j<count($cats[$i]['part']); $j++) {
                        $hearts=$cats[$i]['part'][$j]['editorMark']; 
                        $data[] = array('name'=>$cats[$i]['part'][$j]['name'], 'field1'=>$cats[$i]['part'][$j]['field1'],
                            'field2'=>$cats[$i]['part'][$j]['field2'], 'field3'=>$cats[$i]['part'][$j]['field3'], 
                            'field4'=>$cats[$i]['part'][$j]['field4'], 'mean'=>$cats[$i]['part'][$j]['mean'], 
                            'openDate'=>$cats[$i]['part'][$j]['openDate'], 'oldMean'=>$cats[$i]['part'][$j]['oldMean'], 
                            'oldField1'=>$cats[$i]['part'][$j]['oldField1'], 'oldField2'=>$cats[$i]['part'][$j]['oldField2'], 
                            'oldField3'=>$cats[$i]['part'][$j]['oldField3'], 'oldField4'=>$cats[$i]['part'][$j]['oldField4'], 
                            'votes'=>$cats[$i]['part'][$j]['votes'], 'url'=>$cats[$i]['part'][$j]['url'], 
                            'editorMark'=>$hearts, 'id'=>$j, 'subCats'=>!empty($cats[$i]['part'][$j]['subcats']) ? $cats[$i]['part'][$j]['subcats'] : '', 
                            'openDate'=>date('m.Y', $cats[$i]['part'][$j]['openDate']), 'catId'=>$cats[$i]['part'][$j]['catId'], 
                            'parentId'=>$cats[$i]['part'][$j]['parentId'], 'close'=>$cats[$i]['part'][$j]['isClose']);       
                    }
                }
                $dataProviderArr[] = new CArrayDataProvider($data, array(
                    'sort'=>array('attributes'=> array('name', 'field1', 'field2', 'field3', 'field4', 'mean', 'openDate', 'editorMark', 'close'), 'defaultOrder'=>array('close'=>false)),
                ));
            }
        }
        $lastThemes = Yii::app()->db->createCommand()->select('ft.title, ft.url, p.url as partnerUrl, c.catId, c.parentId')->from('forum_theme ft')->join('partners p', 'p.partnerid=ft.partnerId')->join('partners_cat c', 'c.catId=p.catId')->limit(5)->order('ft.date DESC')->queryAll();
        $lastPosts = Yii::app()->db->createCommand()->select('u.login,t.url, t.title, t.countComments, fc.text, p.url as partnerUrl, c.catId, c.parentId')->from('forum_comments fc')->join('forum_theme t', 't.themeId=fc.themeId and isFirst=0')->join('partners p', 'p.partnerid=t.partnerId')->join('partners_cat c', 'c.catId=p.catId')->leftJoin('users u', 'u.userid=fc.userId')->limit(5)->order('fc.comDate DESC')->queryAll();
        if(!Yii::app()->user->isGuest) 
           $isUserSign = Yii::app()->db->createCommand('select 1 from `subscribers` where `type`="partner" and `userId`='.Yii::app()->user->getId().' limit 1')->query()->read();
        $this->render('index', array('model'=>$model, 'isUserSign'=>!empty($isUserSign) ? true : false, 'lastThemes'=>$lastThemes, 'lastPosts'=>$lastPosts, 'newPartners'=>$newPartners, 'dataProviderArr'=>!empty($dataProviderArr) ? $dataProviderArr : '', 'cats'=>$cats));
    }
    
    public function actionStaticPage($alias) {
        $page = Yii::app()->db->cache(86400, new CacheTaggedDependency(array('pages')))->createCommand()->select('*')->from('pages')->where('`pageUrl`="'.$alias.'"')->limit(1)->queryRow();
        if(!$page) throw new CHttpException(404, 'Не найдено указанной страницы');
        if(!$page['simple']) $this->bannersOff = true;
        $this->render('staticPage', array('page'=>$page));
    }
    
    public function actionUnsubscribe($id) {
        Yii::app()->db->createCommand()->delete('subscribers', 'unsId='.$id);
        $this->render('unsubscribe');
    }
    
    public function actionSubscr($email, $typeId) {
        $validation = (strlen($email) >= 6) && (preg_match("~^([a-z0-9_\-\.])+@([a-z0-9_\-\.])+\.([a-z0-9])+$~i", $email) !== 0);
        if($validation) {
            $theme = Yii::app()->db->createCommand()->select('title')->from('forum_theme')->where("themeId=$typeId")->queryRow();
            if(!empty($theme)) {
                $res = Yii::app()->db->createCommand()->select('id')->from('subscribers')->where("`email`=\"$email\" and `typeid`=$typeId and `type`=\"forum_topic\"")->queryRow();
                if(empty($res)) {
                    $user = Yii::app()->db->createCommand()->select('userid')->from('users')->where("`email`=\"$email\"")->queryRow();
                    Yii::app()->db->createCommand()->insert('subscribers', array('type'=>'forum_topic', 'email'=>$email, 'typeId'=>$typeId, 'userId'=>$user['userid'], 'unsId'=>md5($email.time())));
                } 
            }
        }
        $this->render('subscr', array('res'=>!empty($res) ? $res : '', 'preg_res'=>$validation, 'theme'=>!empty($theme) ? $theme : ''));
    }
    
    public function actionRefLink($name) {
        $partner = Yii::app()->db->createCommand()->select('refLink, type')->from('partners')->where('name="'.$name.'"')->queryRow();
        if(!empty($partner) && $partner['type'] == 'Простая регистрация' && !empty($partner['refLink'])) $this->redirect($partner['refLink']);
        else $this->redirect(array('site/index'));
    }
}